package com.gomcarter.frameworks.base.converter.jackson;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import com.gomcarter.frameworks.base.config.BaseConfProperties;
import com.gomcarter.frameworks.base.json.JsonObject;
import com.gomcarter.frameworks.base.json.SimpleJsonObject;
import com.yifeng.repo.base.security.context.manager.RequestContextManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

import java.io.IOException;
import java.lang.reflect.Type;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Arrays;
import java.util.Collections;
import java.util.Optional;

import static com.yifeng.repo.base.utils.converter.DateHelper.*;

@Slf4j
public class CustomMappingJacksonConverter extends MappingJackson2HttpMessageConverter {
    private final BaseConfProperties properties;

    /**
     * 业务自定义构造
     */
    public CustomMappingJacksonConverter() {
        properties = new BaseConfProperties();
    }

    /**
     * 框架自己构造
     */
    public CustomMappingJacksonConverter(BaseConfProperties properties) {
        super(Jackson2ObjectMapperBuilder.json().featuresToDisable(MapperFeature.IGNORE_DUPLICATE_MODULE_REGISTRATIONS).build());
        this.properties = properties;
        this.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON, MediaType.TEXT_HTML));
        ObjectMapper mapper = this.getObjectMapper();
        if (properties.isIncludeNullField()) {
            mapper.setSerializationInclusion(Include.ALWAYS);
        } else {
            mapper.setSerializationInclusion(Include.NON_NULL);
        }
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.configure(DeserializationFeature.FAIL_ON_NUMBERS_FOR_ENUMS, true);

        // 转换key
        if (properties.isEnablePropertyTransformer()) {
            mapper.setPropertyNamingStrategy(new TransformerPropertyNamingStrategy(
                    Optional.ofNullable(properties.getPropertyTransformerMapping()).orElse(Collections.emptyMap())
            ));
        }

        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
        simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
        mapper.registerModule(simpleModule);

        JavaTimeModule timeModule = new JavaTimeModule();
        timeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DATE_TIME_FORMATTER));
        timeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DATE_FORMATTER));
        timeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(TIME_FORMATTER));
        timeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DATE_TIME_FORMATTER));
        timeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DATE_FORMATTER));
        timeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(TIME_FORMATTER));
        mapper.registerModule(timeModule);
    }

    @Override
    protected void writeInternal(Object object, Type type, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        if (properties.isEnablePropertyTransformer()
                && Boolean.TRUE.equals(RequestContextManager.getTransferRespDataKey())
                && object instanceof JsonObject) {
            SimpleJsonObject simpleObject = new SimpleJsonObject((JsonObject) object);
            super.writeInternal(simpleObject, type, outputMessage);
        } else {
            super.writeInternal(object, type, outputMessage);
        }
    }
}
